/*
 * Copyright (c) 2014, KJFrameForAndroid 张涛 (kymjs123@gmail.com).
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.kymjs.aframe.ui.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.IntentFilter;
import android.os.Handler;
import android.util.Log;
import android.widget.Toast;
import com.jason.bluetooth.fingerprint.AppContext;
import com.jason.bluetooth.fingerprint.beans.RecordBean;
import com.jason.bluetooth.fingerprint.beans.ui.FingerPrintBean;
import com.jason.bluetooth.fingerprint.ui.HomeActivity;
import com.jason.bluetooth.fingerprint.ui.RecordActivity;
import org.kymjs.aframe.KJLoger;
import org.kymjs.aframe.database.KJDB;
import org.kymjs.aframe.ui.KJActivityManager;
import org.kymjs.aframe.ui.ViewInject;

import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Window;
import android.view.WindowManager;
import org.kymjs.aframe.utils.StringUtils;

import java.util.List;

/**
 * Application BaseActivity,you should inherit it for your Activity<br>
 * 
 * <b>创建时间</b> 2014-5-28
 * 
 * @author kymjs(kymjs123@gmail.com)
 * @version 1.2
 */
public abstract class BaseActivity extends KJFrameActivity {

    private static final String TAG = "BaseActivity";
    /**
     * 当前Activity状态
     */
    public static enum ActivityState {
        RESUME, PAUSE, STOP, DESTROY
    }

    /**
     * Activity显示方向
     */
    public static enum ScreenOrientation {
        HORIZONTAL, VERTICAL, AUTO
    }

    public Activity aty;
    /** Activity状态 */
    public ActivityState activityState = ActivityState.DESTROY;
    // 是否允许全屏
    private boolean mAllowFullScreen = false;
    // 是否隐藏ActionBar
    private boolean mHiddenActionBar = true;
    // 是否启用框架的退出界面
    private boolean mOpenBackListener = false;

    // 屏幕方向
    private ScreenOrientation orientation = ScreenOrientation.VERTICAL;

    /**
     * 是否全屏显示本Activity，全屏后将隐藏状态栏，默认不全屏（若修改必须在构造方法中调用）
     * 
     * @param allowFullScreen
     *            是否允许全屏
     */
    public void setAllowFullScreen(boolean allowFullScreen) {
        this.mAllowFullScreen = allowFullScreen;
    }

    /**
     * 是否隐藏ActionBar，默认隐藏（若修改必须在构造方法中调用）
     * 
     * @param hiddenActionBar
     *            是否隐藏ActionBar
     */
    public void setHiddenActionBar(boolean hiddenActionBar) {
        this.mHiddenActionBar = hiddenActionBar;
    }

    /**
     * 修改屏幕显示方向，默认竖屏锁定（若修改必须在构造方法中调用）
     * 
     * @param orientation
     */
    public void setScreenOrientation(ScreenOrientation orientation) {
        this.orientation = orientation;
    }

    /**
     * 是否启用返回键监听，若启用，则在显示最后一个Activity时将弹出退出对话框。默认启用（若修改必须在构造方法中调用）
     * 
     * @param openBackListener
     */
    public void setBackListener(boolean openBackListener) {
        this.mOpenBackListener = openBackListener;
    }

    /**
     * @return 返回是否启用返回键监听
     */
    protected boolean getBackListener() {
        return this.mOpenBackListener;
    }

    /**
     * skip to @param(cls)，and call @param(aty's) finish() method
     */
    @Override
    public void skipActivity(Activity aty, Class<?> cls) {
        showActivity(aty, cls);
        aty.finish();
    }

    /**
     * skip to @param(cls)，and call @param(aty's) finish() method
     */
    @Override
    public void skipActivity(Activity aty, Intent it) {
        showActivity(aty, it);
        aty.finish();
    }

    /**
     * skip to @param(cls)，and call @param(aty's) finish() method
     */
    @Override
    public void skipActivity(Activity aty, Class<?> cls, Bundle extras) {
        showActivity(aty, cls, extras);
        aty.finish();
    }

    /**
     * show to @param(cls)，but can't finish activity
     */
    @Override
    public void showActivity(Activity aty, Class<?> cls) {
        Intent intent = new Intent();
        intent.setClass(aty, cls);
        aty.startActivity(intent);
    }

    /**
     * show to @param(cls)，but can't finish activity
     */
    @Override
    public void showActivity(Activity aty, Intent it) {
        aty.startActivity(it);
    }

    /**
     * show to @param(cls)，but can't finish activity
     */
    @Override
    public void showActivity(Activity aty, Class<?> cls, Bundle extras) {
        Intent intent = new Intent();
        intent.putExtras(extras);
        intent.setClass(aty, cls);
        aty.startActivity(intent);
    }

    /***************************************************************************
     * 
     * print Activity callback methods
     * 
     ***************************************************************************/
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        aty = this;
        KJLoger.state(this.getClass().getName(), "---------onCreat ");
        switch (orientation) {
        case HORIZONTAL:
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
            break;
        case VERTICAL:
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            break;
        case AUTO:
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_USER);
            break;
        }

        if (mHiddenActionBar) {
            requestWindowFeature(Window.FEATURE_NO_TITLE);
        } else {
            ActionBar a = getActionBar();
            a.show();
        }
        if (mAllowFullScreen) {
            getWindow().setFlags(
                    WindowManager.LayoutParams.FLAG_FULLSCREEN,
                    WindowManager.LayoutParams.FLAG_FULLSCREEN);
        }
        super.onCreate(savedInstanceState);
//        initBroadcastReceiver();
    }

    protected void initMatchFingerBroadcastReceiver(){
        IntentFilter filter = new IntentFilter();
        filter.addAction(HomeActivity.ACTION_BLUETOOTH_FINGER_MATCH);
        filter.addAction(HomeActivity.ACTION_BLUETOOTH_CARD);
        filter.addAction(HomeActivity.ACTION_BLUETOOTH_RECORD_CHOOSE);
        registerReceiver(mMatchFingerBroadcastReceiver, filter);
    }

    protected void initRegisterFingerBroadcastReceiver(){
        IntentFilter filter = new IntentFilter();
        filter.addAction(HomeActivity.ACTION_BLUETOOTH_FINGER_REGISTER);
        registerReceiver(mMatchFingerBroadcastReceiver, filter);
    }

    protected void destoryFingerBroadcastReceiver(){
        if (mMatchFingerBroadcastReceiver != null){
            unregisterReceiver(mMatchFingerBroadcastReceiver);
        }
    }


    private BroadcastReceiver mMatchFingerBroadcastReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (!StringUtils.isEmpty(action)){
                int state = 1;
                boolean flag = false;
                int type = 0;
                if (action.equals(HomeActivity.ACTION_BLUETOOTH_FINGER_MATCH)){
                    Log.i(TAG,"----mMatchFingerBroadcastReceiver--ACTION_BLUETOOTH_FINGER_MATCH--->");
                    flag = intent.getBooleanExtra(HomeActivity.FINGER_STATE,false);
                    Log.i(TAG,"----mMatchFingerBroadcastReceiver--ACTION_BLUETOOTH_FINGER_MATCH--->flag:" + flag);
                    state = 1;
                    matchFingerResult(state,flag);
                }else if(action.equals(HomeActivity.ACTION_BLUETOOTH_CARD)){
                    Log.i(TAG,"----mMatchFingerBroadcastReceiver--ACTION_BLUETOOTH_CARD--->");
                    Log.i(TAG,"----mMatchFingerBroadcastReceiver--ACTION_BLUETOOTH_CARD--->CARD_VALUE:" + HomeActivity.CARD_VALUE);
                    flag = intent.getBooleanExtra(HomeActivity.CARD_STATE,false);
                    Log.i(TAG,"----mMatchFingerBroadcastReceiver--ACTION_BLUETOOTH_CARD--->flag:" + flag);
                    state = 2;
                    matchFingerResult(state,flag);
                } else if (action.equals(HomeActivity.ACTION_BLUETOOTH_RECORD_CHOOSE)){
                    RecordBean recordBean = HomeActivity.RECORD_INFO;
                    Log.i(TAG,"----mMatchFingerBroadcastReceiver--ACTION_BLUETOOTH_RECORD_CHOOSE--->");
                    String [] actionParam = new String[2];
                    if (recordBean == null){
                        type = 0;
                        HomeActivity.FINGER_TYPE = 0;
                        Toast.makeText(context,"选取失败",Toast.LENGTH_SHORT).show();
                    }else {
                        Log.i(TAG,"----mMatchFingerBroadcastReceiver--ACTION_BLUETOOTH_RECORD_CHOOSE--->" + recordBean.toString());
                        String fp1 = recordBean.getFp_1();
                        String fp2 = recordBean.getFp_2();
                        String card = recordBean.getCardNO();
                        if (!StringUtils.isEmpty(fp1) && !StringUtils.isEmpty(fp2)){
                            actionParam[0] = HomeActivity.ACTION_BLUETOOTH_FINGER_OPEN_MATCH;
                            HomeActivity.FINGER_VALUE = fp1;
                            HomeActivity.FINGER_TYPE = 1;
                        }else if (StringUtils.isEmpty(fp1) && !StringUtils.isEmpty(fp2)){
                            actionParam[0] = HomeActivity.ACTION_BLUETOOTH_FINGER_OPEN_MATCH;
                            HomeActivity.FINGER_VALUE = fp2;
                            HomeActivity.FINGER_TYPE = 2;
                        }else if (!StringUtils.isEmpty(fp1) && StringUtils.isEmpty(fp2)){
                            actionParam[0] = HomeActivity.ACTION_BLUETOOTH_FINGER_OPEN_MATCH;
                            HomeActivity.FINGER_VALUE = fp1;
                            HomeActivity.FINGER_TYPE = 1;
                        }
                        if (!StringUtils.isEmpty(card)){
                            Log.i(TAG,"----mMatchFingerBroadcastReceiver--ACTION_BLUETOOTH_RECORD_CHOOSE--->card：" + card);
                            actionParam[1] = HomeActivity.ACTION_BLUETOOTH_CARD_OPEN;
//                            Intent ii = new Intent();
//                            ii.setAction(HomeActivity.ACTION_BLUETOOTH_CARD_OPEN);
//                            sendBroadcast(ii);
                        }
                        matchFingerStart(actionParam);
                    }
                }
            }
        }
    };

    /***
     *
     * @param state 1:表示指纹，2：表示打卡,3代表失败
     * @param flag true，成功，false,失败
     */
    protected  void matchFingerResult(int state,boolean flag){
        String card = HomeActivity.CARD_VALUE;
        if (!flag){
            if (state == 2){
                Toast.makeText(getApplicationContext(), "打卡失败",
                        Toast.LENGTH_SHORT).show();
                matchFingerCallBack(4,false);
            }else{
                Toast.makeText(getApplicationContext(), "没有找到匹配的指纹",
                        Toast.LENGTH_SHORT).show();
                matchFingerCallBack(3,false);
            }
            return;
        }
        Log.i(TAG,"----matchFingerResult---card:" + card);
        Log.i(TAG,"----matchFingerResult---FINGER_ID:" + HomeActivity.FINGER_ID);
        KJDB mKjdb = AppContext.getInstance().getKjdb();
        //成功
        if (state == 1){
            //指纹
            matchFingerCallBack(1,true);
        }else if (state == 2){
            //打卡
            String where = " type = 1 and cardNo = '" + card + "'";
            List<FingerPrintBean> fingerPrintBeans = null;
            try{
                fingerPrintBeans = mKjdb.findAllByWhere(FingerPrintBean.class,where);
            }catch (Exception e){
                matchFingerCallBack(4,false);
            }
            if (fingerPrintBeans != null && !fingerPrintBeans.isEmpty()){
                //TODO 提示成功
                HomeActivity.FINGER_ID = fingerPrintBeans.get(0).getId();
                matchFingerCallBack(2,true);
//                        addSignInRecord(HomeActivity.FINGERPRINT_BEAN);
            }else{
                matchFingerCallBack(4,false);
                Toast.makeText(getApplicationContext(), "没有找到匹配的指纹",
                        Toast.LENGTH_SHORT).show();
            }
        }
    }


    protected  void matchFingerCallBack(int state,boolean flag){

    }

    /***
     * 发送开始验证指纹或者打开的广播
     */
    protected  void matchFingerStart(String... action){
        if (action != null && action.length > 0){
            for (int i = 0; i < action.length ; i ++){
                String ac = action[i];
                if (!StringUtils.isEmpty(ac)){
                    Log.i(TAG, "-----matchFingerStart--->action:" + ac);
                    Intent intent = new Intent();
                    intent.setAction(ac);
                    sendBroadcast(intent);
                }
            }
        }
    }

    /***
     * 选取人员信息之后通知
     */
    protected void chooseRecordResult(){
        HomeActivity.FINGER_TYPE = 0;
        Intent intent = new Intent();
        intent.setAction(HomeActivity.ACTION_BLUETOOTH_RECORD_CHOOSE);
        sendBroadcast(intent);
    }

    /***
     * 开始选取人员信息
     * 2015年4月8日17:22:28 修改为发送打来指纹和卡的广播
     * @param context
     */
    protected  void chooseRecordStart(Context context){
        if (!HomeActivity.mBlueToothSate){
            Toast.makeText(context,"请先开启蓝牙",Toast.LENGTH_SHORT).show();
        }else{
            matchFingerStart(new String[]{HomeActivity.ACTION_BLUETOOTH_CARD_OPEN,HomeActivity.ACTION_BLUETOOTH_FINGER_OPEN_MATCH});
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        KJLoger.state(this.getClass().getName(), "---------onStart ");
    }

    @Override
    protected void onResume() {
        super.onResume();
        activityState = ActivityState.RESUME;
        KJLoger.state(this.getClass().getName(), "---------onResume ");
    }

    @Override
    protected void onPause() {
        super.onPause();
        activityState = ActivityState.PAUSE;
        KJLoger.state(this.getClass().getName(), "---------onPause ");
    }

    @Override
    protected void onStop() {
        super.onResume();
        activityState = ActivityState.STOP;
        KJLoger.state(this.getClass().getName(), "---------onStop ");
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        KJLoger.state(this.getClass().getName(),
                "---------onRestart ");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        activityState = ActivityState.DESTROY;
        KJLoger.state(this.getClass().getName(),
                "---------onDestroy ");
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (mOpenBackListener && keyCode == KeyEvent.KEYCODE_BACK
                && KJActivityManager.create().getCount() < 1) {
            ViewInject.create().getExitDialog(this);
        }
        return super.onKeyDown(keyCode, event);
    }
}
